import React, { useState, useContext, useRef } from "react";
import FormContext from "../../context/user/formContext";
import MaterialContext from "../../context/suppiler/materialContext";
import FormQueryContext from "../../context/user/formQueryContext";
import Dropdown from "../../components/dropdown";
import ScrollPicker from "../../components/ScrollPicker";
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from "react-native";
import { Entypo } from "@expo/vector-icons";
import { AntDesign } from "@expo/vector-icons";

const dimen = Dimensions.get("window");
const width = dimen.width;

const FormScreen = ({ navigation }) => {
  const processOptions = (arr) => {
    let options = [];
    arr.map((item) => {
      options.push(item.type);
    });
    return options;
  };

  const { formData, editData, addData, deleteFormItem } =
    useContext(FormContext);
  // console.log("formData----", formData);
  const { material } = useContext(MaterialContext);
  // console.log("material----", material);
  const { selectPrice } = useContext(FormQueryContext);

  // 行业内所有材料
  const categories = material.map((item) => {
    return item.category;
  });
  const AllTypes = [];
  material.map((item, index) => {
    let t_material = processOptions(item.types);
    t_material.unshift("");
    t_material.push("");
    AllTypes.push(t_material);
  });
  categories.unshift("");
  categories.push("");

  const shapeList = ["长方形", "圆形"];
  const [baseCategory, setBaseCategory] = useState(0);
  const [shroudCategory, setShroudCategory] = useState(0);

  // console.log("pppppppp====", formData);

  const t_visible = [];
  formData.map(() => {
    t_visible.push(false);
  });
  const [itemsVisible, setItemsVisible] = useState(t_visible);
  // console.log("2---", itemsVisible);

  const cardVisible = (key, value) => {
    // const temp = itemsVisible;
    // temp[index] = false;
    setItemsVisible(
      itemsVisible.map((item, index) => {
        return index == key ? value : item;
      })
    );
    // console.log("3---", itemsVisible);
  };

  const addGood = () => {
    addData({
      type: categories[0] + categories[0],
      detail: {
        specs: {
          shape: [1, ""],
          length: ["1", 2],
          width: ["1", 2],
          radius: ["1", 2],
        },
        basePlate: {
          category: [0, categories[0]],
          thickness: ["1", 2],
          type: [0, processOptions(material[0].types)[0]],
        },
        shroudPlate: {
          category: [0, categories[0]],
          thickness: ["1", 2],
          type: [1, processOptions(material[0].types)[0]],
        },
        amount: "",
      },
    });
    itemsVisible.push(true);
  };

  let currentVisible = useRef();
  currentVisible.current = itemsVisible;

  return (
    <View style={styles.container}>
      <ScrollView
        vertical={true} // 垂直方向
        showsHorizontalScrollIndicator={false} // 隐藏水平指示器
        showsVerticalScrollIndicator={false} // 隐藏垂直指示器
        style={{ paddingBottom: 150 }}
      >
        <View style={{ marginTop: 20, marginLeft: 20 }}>
          <Text style={{ color: "#999", fontSize: 13 }}>
            *点击条目将其展开可以进行修改！
          </Text>
        </View>
        {formData.map((formItem, index) => {
          return (
            <View
              style={[
                styles.addModal,
                currentVisible.current[index]
                  ? null
                  : { paddingTop: 10, paddingBottom: 10, borderRadius: 10 },
              ]}
              key={index}
            >
              <View
                style={{
                  flexDirection: "row",
                  // justifyContent: "center",
                  alignItems: "center",
                  marginBottom: 3,
                  marginTop: 2,
                }}
              >
                <Entypo name="controller-record" size={15} color="#51bfe5" />
                {/*  */}
                {currentVisible.current[index] ? (
                  <TouchableOpacity
                    onPress={() => cardVisible(index, !itemsVisible[index])}
                  >
                    <View style={{ width: width }}>
                      <Text
                        style={[styles.bigTitle, { alignSelf: "flex-start" }]}
                      >
                        {formItem.detail.basePlate.category[1] +
                          formItem.detail.basePlate.type[1] +
                          "*" +
                          formItem.detail.shroudPlate.category[1] +
                          formItem.detail.shroudPlate.type[1]}
                      </Text>
                    </View>
                  </TouchableOpacity>
                ) : (
                  <View style={{ flexDirection: "row" }}>
                    <View
                      style={{
                        flexDirection: "column",
                      }}
                    >
                      <TouchableOpacity
                        onPress={() => cardVisible(index, !itemsVisible[index])}
                      >
                        <View>
                          <Text
                            style={{
                              marginLeft: 10,
                              fontSize: 15,
                              color: "#22254c",
                              fontWeight: "900",
                            }}
                          >
                            {formItem.detail.basePlate.category[1] +
                              formItem.detail.basePlate.type[1] +
                              "*" +
                              formItem.detail.shroudPlate.category[1] +
                              formItem.detail.shroudPlate.type[1]}
                          </Text>
                        </View>
                        <View
                          style={{
                            flexDirection: "row",
                          }}
                        >
                          <Text
                            style={{
                              color: "#999",
                              fontSize: 13,
                              marginLeft: 10,
                              marginTop: 7,
                              width: 220,
                            }}
                          >
                            {formItem.detail.specs.shape[0] == 0
                              ? "(" +
                                formItem.detail.basePlate.thickness[0] +
                                "+" +
                                formItem.detail.shroudPlate.thickness[0] +
                                ")" +
                                "*" +
                                formItem.detail.specs.length[0] +
                                "*" +
                                formItem.detail.specs.width[0]
                              : "(" +
                                formItem.detail.basePlate.thickness[0] +
                                "+" +
                                formItem.detail.shroudPlate.thickness[0] +
                                ")" +
                                "Φ" +
                                formItem.detail.specs.radius[0]}
                          </Text>
                        </View>
                      </TouchableOpacity>
                    </View>
                    <View style={{ marginRight: 100, flexDirection: "column" }}>
                      <View>
                        <TouchableOpacity onPress={() => deleteFormItem(index)}>
                          <Text
                            style={{
                              color: "#bbb",
                              fontSize: 13,
                              marginLeft: 13,
                            }}
                          >
                            删除
                          </Text>
                        </TouchableOpacity>
                      </View>
                      <View
                        style={{
                          marginTop: 6,
                          flexDirection: "row",
                          paddingLeft: 2,
                          paddingRight: 2,
                          borderColor: "#ddd",
                          borderWidth: 1,
                          borderRadius: 5,
                          // marginTop: 20,
                        }}
                      >
                        <AntDesign
                          name="close"
                          size={10}
                          color="#999"
                          style={{ marginTop: 7, marginRight: 2 }}
                        />
                        <Text sty={{ fontSize: 12 }}>
                          {formItem.detail.amount == ""
                            ? "0"
                            : formItem.detail.amount}
                        </Text>
                      </View>
                    </View>
                  </View>
                )}
              </View>

              {currentVisible.current[index] ? (
                <View style={{ justifyContent: "center", marginTop: 4 }}>
                  <View style={styles.addItems}>
                    <View style={styles.addItem}>
                      <Text style={styles.title}>基板:</Text>
                      <View style={styles.inputView}>
                        <ScrollPicker
                          selectedIndex={[
                            formData[index].detail.basePlate.category[0],
                            formData[index].detail.basePlate.type[0],
                          ]}
                          options={[categories, AllTypes]}
                          onSubmit={(index1, category, index2, type) => {
                            setBaseCategory(index1);
                            formData[index].detail.basePlate.category[1] =
                              category;
                            formData[index].detail.basePlate.category[0] =
                              index1;
                            formData[index].detail.basePlate.type[0] = index2;
                            formData[index].detail.basePlate.type[1] = type;
                            formData[index].type =
                              category +
                              formData[index].detail.shroudPlate.category[1];
                            editData(index, formData[index]);
                          }}
                        ></ScrollPicker>
                      </View>
                      {/* <Dropdown
                        ifFirst={1}
                        initialValues={{
                          initKey: formItem.detail.basePlate.category[0],
                          initOptions: categories,
                        }}
                        initialStyles={{
                          valueWith: 230,
                          valueMarginTop: 0,
                          optionsWidth: 110,
                          optionsBackGroundColor: "#eee",
                          optionsBorderColor: "#ccc",
                        }}
                        onSelect={(item, value) => {
                          setBaseCategory(value);
                          formData[index].detail.basePlate.category[1] = item;
                          formData[index].detail.basePlate.category[0] = value;
                          formData[index].detail.basePlate.type[0] = 0;
                          formData[index].detail.basePlate.type[1] =
                            processOptions(
                              material[formItem.detail.basePlate.category[0]]
                                .types
                            )[0];
                          formData[index].type =
                            item +
                            formData[index].detail.shroudPlate.category[1];
                          editData(index, formData[index]);
                        }}
                      /> */}
                    </View>
                    {/* <View style={styles.addItem}>
                      <Text style={styles.title}>型号:</Text>
                      <Dropdown
                        ifFirst={1}
                        initialValues={{
                          initKey: formItem.detail.basePlate.type[0],
                          initOptions: processOptions(
                            material[formItem.detail.basePlate.category[0]]
                              .types
                          ),
                        }}
                        initialStyles={{
                          valueWith: 230,
                          valueMarginTop: 0,
                          optionsWidth: 110,
                          optionsBackGroundColor: "#eee",
                          optionsBorderColor: "#ccc",
                        }}
                        onSelect={(item, value) => {
                          formData[index].detail.basePlate.type[0] = value;
                          formData[index].detail.basePlate.type[1] = item;
                          editData(index, formData[index]);
                        }}
                      />
                    </View> */}
                    <View style={styles.addItem}>
                      <Text style={styles.title}>厚度:</Text>
                      <TextInput
                        style={{ marginLeft: 20 }}
                        value={formItem.detail.basePlate.thickness[0]}
                        keyboardType="numeric"
                        textAlign="center"
                        onChangeText={(text) => {
                          formData[index].detail.basePlate.thickness[0] = text;
                          editData(index, formData[index]);
                        }}
                        placeholder="请输入长度"
                      />
                      <Text>毫米(mm)</Text>
                    </View>
                  </View>
                  <View style={styles.addItems}>
                    <View style={styles.addItem}>
                      <Text style={styles.title}>覆板:</Text>
                      <View style={styles.inputView}>
                        <ScrollPicker
                          selectedIndex={[
                            formData[index].detail.shroudPlate.category[0],
                            formData[index].detail.shroudPlate.type[0],
                          ]}
                          options={[categories, AllTypes]}
                          onSubmit={(index1, category, index2, type) => {
                            setShroudCategory(index1);
                            formData[index].detail.shroudPlate.category[1] =
                              category;
                            formData[index].detail.shroudPlate.category[0] =
                              index1;
                            formData[index].detail.shroudPlate.type[0] = index2;
                            formData[index].detail.shroudPlate.type[1] = type;
                            formData[index].type =
                              formData[index].detail.basePlate.category[1] +
                              category;
                            editData(index, formData[index]);
                          }}
                        ></ScrollPicker>
                      </View>
                      {/* <Dropdown
                        ifFirst={1}
                        initialValues={{
                          initKey: formItem.detail.shroudPlate.category[0],
                          initOptions: categories,
                        }}
                        initialStyles={{
                          valueWith: 230,
                          valueMarginTop: 0,
                          optionsWidth: 110,
                          optionsBackGroundColor: "#eee",
                          optionsBorderColor: "#ccc",
                        }}
                        onSelect={(item, value) => {
                          setShroudCategory(value);
                          formData[index].detail.shroudPlate.category[1] = item;
                          formData[index].detail.shroudPlate.category[0] =
                            value;
                          formData[index].detail.shroudPlate.type[0] = 0;
                          formData[index].detail.shroudPlate.type[1] =
                            processOptions(
                              material[formItem.detail.shroudPlate.category[0]]
                                .types
                            )[0];
                          formData[index].type =
                            formData[index].detail.basePlate.category[1] + item;
                          editData(index, formData[index]);
                        }}
                      /> */}
                    </View>
                    {/* <View style={styles.addItem}>
                      <Text style={styles.title}>型号:</Text>
                      <Dropdown
                        ifFirst={1}
                        initialValues={{
                          initKey: formItem.detail.shroudPlate.type[0],
                          initOptions: processOptions(
                            material[formItem.detail.shroudPlate.category[0]]
                              .types
                          ),
                        }}
                        initialStyles={{
                          valueWith: 230,
                          valueMarginTop: 0,
                          optionsWidth: 110,
                          optionsBackGroundColor: "#eee",
                          optionsBorderColor: "#ccc",
                        }}
                        onSelect={(item, value) => {
                          formData[index].detail.shroudPlate.type[0] = value;
                          formData[index].detail.shroudPlate.type[1] = item;
                          editData(index, formData[index]);
                        }}
                      />
                    </View> */}
                    <View style={styles.addItem}>
                      <Text style={styles.title}>厚度:</Text>
                      <TextInput
                        style={{ marginLeft: 20 }}
                        value={formItem.detail.shroudPlate.thickness[0]}
                        keyboardType="numeric"
                        textAlign="center"
                        onChangeText={(text) => {
                          formData[index].detail.shroudPlate.thickness[0] =
                            text;
                          editData(index, formData[index]);
                        }}
                        placeholder="请输入厚度"
                      />
                      <Text>毫米(mm)</Text>
                    </View>
                  </View>
                  <View style={styles.addItems}>
                    <View
                      style={[
                        styles.addItem,
                        { justifyContent: "flex-start", flexWrap: "wrap" },
                      ]}
                    >
                      <Text style={styles.title}>形状:</Text>
                      <View style={{ flexDirection: "row" }}>
                        {shapeList.map((tag, key) => {
                          return (
                            <TouchableOpacity
                              style={{ marginLeft: 35 }}
                              key={key}
                              onPress={() => {
                                formData[index].detail.specs.shape[1] = tag;
                                formData[index].detail.specs.shape[0] = key;
                                editData(index, formData[index]);
                              }}
                            >
                              <Text
                                style={
                                  key === formItem.detail.specs.shape[0]
                                    ? styles.selectedTag
                                    : styles.tag
                                }
                              >
                                {tag}
                              </Text>
                            </TouchableOpacity>
                          );
                        })}
                      </View>
                    </View>
                    {formItem.detail.specs.shape[0] == 0 ? (
                      <View>
                        <View style={styles.addItem}>
                          <Text style={styles.title}>长度:</Text>
                          <TextInput
                            style={{ marginLeft: 20 }}
                            value={formItem.detail.specs.length[0]}
                            keyboardType="numeric"
                            textAlign="center"
                            onChangeText={(length) => {
                              formData[index].detail.specs.length[0] = length;
                              editData(index, formData[index]);
                            }}
                            placeholder="请输入长度"
                          />
                          <Text>毫米(mm)</Text>
                        </View>
                        <View style={styles.addItem}>
                          <Text style={styles.title}>宽度:</Text>
                          <TextInput
                            style={{ marginLeft: 20 }}
                            value={formItem.detail.specs.width[0]}
                            keyboardType="numeric"
                            textAlign="center"
                            onChangeText={(length) => {
                              formData[index].detail.specs.width[0] = length;
                              editData(index, formData[index]);
                            }}
                            placeholder="请输入长度"
                          />
                          <Text>毫米(mm)</Text>
                        </View>
                      </View>
                    ) : (
                      <View style={styles.addItem}>
                        <Text style={styles.title}>直径:</Text>
                        <TextInput
                          style={{ marginLeft: 20 }}
                          value={(
                            formItem.detail.specs.radius[0] * 2
                          ).toString()}
                          keyboardType="numeric"
                          textAlign="center"
                          onChangeText={(text) => {
                            formData[index].detail.specs.radius[0] = text / 2;
                            editData(index, formData[index]);
                          }}
                          placeholder="请输入直径"
                        />
                        <Text>毫米(mm)</Text>
                      </View>
                    )}
                    <View style={styles.addItem}>
                      <Text style={styles.title}>数量:</Text>
                      <TextInput
                        style={{
                          marginRight: 25,
                          width: 200,
                        }}
                        value={formItem.detail.amount}
                        keyboardType="numeric"
                        textAlign="center"
                        onChangeText={(amount) => {
                          formData[index].detail.amount = amount;
                          editData(index, formData[index]);
                        }}
                        placeholder="请输入数量"
                      />
                    </View>
                  </View>
                  <View>
                    <TouchableOpacity onPress={() => cardVisible(index, false)}>
                      <Text style={{ color: "#1E90FF", marginLeft: "90%" }}>
                        完成
                      </Text>
                    </TouchableOpacity>
                  </View>
                </View>
              ) : null}
            </View>
          );
        })}
        <View
          style={{
            height: 45,
            width: "88%",
            marginTop: 30,
            alignSelf: "center",
            marginBottom: 200,
            flexDirection: "row",
          }}
        >
          <TouchableOpacity
            style={styles.add}
            onPress={() => {
              addGood();
            }}
          >
            <Text style={styles.addText}>添加商品</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.confirm}
            onPress={() => {
              editData(formData), navigation.navigate("FormQuery");
              selectPrice(formData);
            }}
          >
            <Text style={styles.confirmText}>开始计算</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "#fff",
    // paddingBottom: 100,
  },
  addModal: {
    justifyContent: "center",
    // height: 500,
    backgroundColor: "#fff",
    padding: 20,
    width: width * 0.9,
    margin: width * 0.05,
    marginBottom: 0,
    borderRadius: 20,
    elevation: 10, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 0,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
    flexDirection: "column",
  },
  bigTitle: {
    marginLeft: 5,
    fontSize: 17,
    color: "#22254c",
    alignSelf: "center",
    fontWeight: "900",
  },
  addItems: {
    // backgroundColor: "pink",
    margin: 10,
    marginRight: 7,
  },
  addItem: {
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 3,
    marginBottom: 5,
    alignItems: "center",
  },
  title: {
    fontSize: 15,
    color: "#22254c",
  },
  add: {
    marginRight: 20,
    borderRadius: 5,
    flex: 4,
    padding: 10,
    borderColor: "#51bfe5",
    borderWidth: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  addText: {
    fontSize: 16,
    color: "#51bfe5",
    fontWeight: "bold",
  },
  confirm: {
    borderRadius: 5,
    flex: 7,
    padding: 10,
    backgroundColor: "#51bfe5",
    alignItems: "center",
    justifyContent: "center",
    elevation: 2, //设置阴影角度，通过这个设置有无阴影
    shadowColor: "gray", // 设置阴影色
  },
  confirmText: {
    fontSize: 16,
    color: "#fff",
    fontWeight: "bold",
  },
  tag: {
    borderWidth: 1,
    borderColor: "#d1d1d6",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#d1d1d6",
    fontSize: 14,
  },
  selectedTag: {
    borderWidth: 1,
    borderColor: "#51bfe5",
    padding: 1,
    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#51bfe5",
  },
  inputView: {
    justifyContent: "center",
    width: "85%",
    borderColor: "#51bfe5",
    // borderBottomWidth: 1,
    flexDirection: "row",
    alignItems: "center",
    paddingRight: 10,
  },
});

export default FormScreen;
